//
//  DrawerViewController.m
//  DrawerViewController
//
//  Created by 李含文 on 16/7/22.
//  Copyright © 2016年 SK丿希望. All rights reserved.
//

#import "DrawerViewController.h"

#define screenW [UIScreen mainScreen].bounds.size.width

@interface DrawerViewController ()
/** 用于记录mainV的当前位置 */
@property (nonatomic, assign) CGFloat x;
@end

@implementation DrawerViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 添加view
    [self addView];
    
    // 给主View添加手势
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
    // 添加手势
    [self.mainV addGestureRecognizer:pan];
    
    
    
}

// 监听手势
- (void)pan:(UIPanGestureRecognizer *)pan {
    
    // 获取偏移量
    CGPoint transP = [pan translationInView:self.mainV];
    //    NSLog(@"X=%f Y=%f", transP.x, transP.y);
    
    // 调用方法计算位置
    [self setFrameWithOffset:transP.x];
    // 判断手势的状态
    if(pan.state == UIGestureRecognizerStateEnded) {
        // 如果拖动不到一半 回到初始位置
        if (self.mainV.frame.origin.x <= screenW * 0.5) {
            [self closeDrawer];
        } else {
            // 大于一半
            [self openDrawer];
        }
    }
    
    
    if (self.mainV.frame.origin.x == screenW * 0.75) {
        
    }
    
    NSLog(@"%f", self.x);
}

// 根据手势滑动的位置设置View的位置
- (void)setFrameWithOffset:(CGFloat)offset {
    // 平移
    CGRect frame = self.mainV.frame;
    frame.origin.x = self.x + offset; // 在次滑动时值为0
    self.mainV.frame = frame;
    //只能往右边拖动
    //    if (frame.origin.x <= 0) {
    //        self.mainV.frame = self.view.bounds;
    //    }
    
}

// 打开抽屉
- (void)openDrawer {
    [UIView animateWithDuration:0.25 animations:^{
        CGRect frame = self.mainV.frame;
        frame.origin.x = screenW * 0.75;
        self.x = frame.origin.x;
        self.mainV.frame = frame;
    }];
}
// 关闭抽屉
- (void)closeDrawer {
    [UIView animateWithDuration:0.25 animations:^{
        self.mainV.frame = self.view.bounds;
        self.x = 0;
        self.mainV.transform = CGAffineTransformIdentity;
    }];
}




#pragma mark - 添加View
/**
 添加View
 */
- (void)addView {
    // 添加左边View (设置其frame等于当前View的bounds)
    UIView *leftV = [[UIView alloc] initWithFrame:self.view.bounds];
    leftV.backgroundColor = [UIColor blueColor];
    // 添加到控制器View
    [self.view addSubview:leftV];
    _leftV = leftV;
    
    
    // 添加mainView(设置其frame等于当前View的bounds)(注意:因为是后添加的故看的是他)
    UIView *mainV = [[UIView alloc] initWithFrame:self.view.bounds];
    mainV.backgroundColor = [UIColor redColor];
    // 添加到控制器View
    [self.view addSubview:mainV];
    _mainV = mainV;
}

@end
